
<template>
  <div class="login-container">
    <div class="login-card">
      <h1 class="login-title">用户登录</h1>

      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
              id="username"
              v-model="username"
              type="text"
              placeholder="请输入用户名"
              required
              class="form-input"
              @keydown.enter="focusPassword"
              ref="usernameInput"
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
              id="password"
              v-model="password"
              type="password"
              placeholder="请输入密码"
              required
              class="form-input"
              ref="passwordInput"
          />
        </div>

        <div class="form-options">
          <label class="checkbox-label">
            <input
                v-model="rememberMe"
                type="checkbox"
                class="checkbox-input"
            />
            <span>记住我</span>
          </label>

          <a href="#" class="forgot-link">忘记密码？</a>
        </div>

        <div class="form-actions">
          <button type="submit" class="login-btn">登录</button>
          <button type="button" @click="handleReset" class="reset-btn">重置</button>
        </div>
      </form>

      <div class="login-footer">
        <p>还没有账号？<a href="#" class="register-link">立即注册</a></p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  width: 1280px;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
}

.login-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  text-align: left;
}

.form-group label {
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.form-input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  cursor: pointer;
}

.checkbox-input {
  width: 16px;
  height: 16px;
}

.forgot-link {
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
}

.forgot-link:hover {
  text-decoration: underline;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 10px;
}

.login-btn {
  flex: 1;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s ease;
}

.login-btn:hover {
  background: #5a6fd8;
}

.reset-btn {
  flex: 1;
  padding: 12px;
  background: #f8f9fa;
  color: #666;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: #e9ecef;
}

.login-footer {
  text-align: center;
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  color: #666;
}

.register-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.register-link:hover {
  text-decoration: underline;
}
</style>

<script setup lang="ts">
import {nextTick, ref} from 'vue'
import api from '@/utils/api'

// 响应式数据
const username = ref('')
const password = ref('')
const rememberMe = ref(false)
const isLoading = ref(false)
const loginError = ref('')

// 模板引用
const usernameInput = ref<HTMLInputElement | null>(null)
const passwordInput = ref<HTMLInputElement | null>(null)

// 聚焦到密码框
const focusPassword = () => {
  nextTick(() => {
    passwordInput.value?.focus()
  })
}

// 登录方法
const handleLogin = async () => {
  // 清除之前的错误信息
  loginError.value = ''

  // 设置加载状态
  isLoading.value = true

  try {
    // 调用登录接口
    // const response = await api.get('/informatization/basicDto4Like') //随便找个get接口测试
    const response = await api.post('/login', {
      username: username.value,
      password: password.value,
    })

    const data = response.data

    // 根据后端返回的数据结构进行处理
    // 假设成功返回包含 token 或 userInfo
    if (data.success || data.token) {
      // 登录成功处理
      console.log('登录成功:', data)

      // 如果选择了记住我，保存到 localStorage，否则保存到 sessionStorage
      const storage = rememberMe.value ? localStorage : sessionStorage
      if (data.token) {
        storage.setItem('token', data.token)
      }
      if (data.userInfo) {
        storage.setItem('userInfo', JSON.stringify(data.userInfo))
      }

      // 显示成功消息
      alert('登录成功！')

      // 在实际项目中，这里通常会跳转到首页或其他页面
      // router.push('/dashboard')

      // 重置表单
      handleReset()
    } else {
      // 登录失败
      loginError.value = data.message || '登录失败，请检查用户名和密码'
    }
  } catch (error: any) {
    console.error('登录错误:', error)

    // 根据错误类型显示不同的错误信息
    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status
      if (status === 401) {
        loginError.value = '用户名或密码错误'
      } else if (status === 404) {
        loginError.value = '登录接口不存在'
      } else if (status >= 500) {
        loginError.value = '服务器错误，请稍后重试'
      } else {
        loginError.value = error.response.data?.message || `请求失败 (${status})`
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      loginError.value = '网络错误，请检查网络连接或服务器是否运行'
    } else {
      // 其他错误
      loginError.value = '登录失败，请稍后重试'
    }
  } finally {
    isLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  username.value = ''
  password.value = ''
  rememberMe.value = false
  nextTick(() => {
    usernameInput.value?.focus()
  })
}
</script>
